import React from 'react';
import ReactDOM from 'react-dom';
import { Table, Form, Input, Button ,Select, Row, Col, DatePicker, Icon, Message  } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;

let uuid = 0;
let PayFree = React.createClass({

  contextTypes: {
    router: React.PropTypes.object
  },

  getInitialState() {
    return {
      loading: false,
      data: null,
      options: '',
      optionsKey: {},
      isFixed: false,
      curList: {},
      costArry: [],
      dataList: {},

    }
  },
  componentDidMount(){
    this.fetch();
  },

  fetch(){
    Utils.sendAjax({
      url: '/tenement/cost/kindList',
      callback: (result) => {
        if (result.code === '200') {
          this.optionRender(result.data)

        } else {
          Message.error(result.message, 10);
        }
      }
    });
  },

  optionRender(data) {
    if(!data[0]) {return }
    let newDom = []
    data.forEach((item, index)=> {
      let opt = (
        <Option key={index} value={item.costNid} >{item.costName}</Option>
      );
      newDom.push(opt);
    })
    return this.setState({
      data: newDom,
      options: data
    });
  },


  // 获取输入框的值
  handleChange(field, value) {
    let k = field.target ? '' : field.split('-')[1];
    let t = field.target ? field.target.value : ((field == 'costNid-'+k) ? value : Utils.formatDate(value));
    let name = field.target ? field.target.id : field
    let newTime = this.state.dataList;
    if (field == 'costNid-'+k  ) {
      for(let o in newTime) {
        if (value == newTime[o]) {
          this.remove(k);
          return Message.error('不能选取相同收费类型', 10)
        }
      }
    }
    if (!newTime['rentId'+'-'+k]) {
      newTime['rentId'+'-'+k] = '';
    }
    if (value == 'tRent' || value == 'tDeposit') {
      this.fetchInfo(k, value);
    } else {
      if (field == 'costNid-'+k) {
        this.clearSet(k, value)
      }
    }
    newTime[name] = t;

    this.setState({
      dataList: newTime,
      //optionsKey: newStr
    });
    this.optionRender(this.state.options)
  },


  clearSet(k, value) {
    let obj = this.state.dataList;
    if (value !== 'tRent' && value !== 'tDeposit') {
      for(let o in obj) {
        let arr = o.split('-');
        if (arr[1] == k) {
          obj[o] = null;
        }
      }
    }

  },
  // 添加一行费用项
  add() {
    uuid++;
    const { form } = this.props;

    console.log(form)
    let keys = form.getFieldValue('keys');
    keys = keys.concat(uuid);
    form.setFieldsValue({
      keys,
    });
  },

  remove(k){
    const { form } = this.props;
    let keys = form.getFieldValue('keys');
    keys = keys.filter((key) => {
      return key !== k;
    });
    this.deleteOptionKey(k)
    form.setFieldsValue({
      keys,
    });
  },

  deleteOptionKey(k) {
    let key = this.state.dataList['costNid-'+k];
    let disKey = this.state.optionsKey;
    console.log(key)
    for(let o in disKey) {
      if (disKey[o] == key) {
        disKey[o] = ''
      }
    }
    this.setState({
      optionsKey: disKey
    })
    this.optionRender(this.state.options);
  },

  handleSubmit(e){
    let current = this.state.dataList;
    let costArry = this.setFieldArr(current);
    let id = this.props.location.state
    let param = {costlist: costArry}
    let params = Object.assign({}, param, id);
    console.log(params)
    this.props.form.validateFields((errors, values) => {
      if (!!errors) {
        console.log('Errors in form!!!');
        return;
      }
      this.setState({
        loading: true,
      });
      Utils.sendAjax({
        url: '/tenement/cost/add',
        data: JSON.stringify(params),
        callback: (result) => {
          if (result.code === '200') {
            let params = this.props.location.state;
            let goPathUrl = '/landlord/houseResource/history';
            this.context.router.push({pathname: goPathUrl, state: {...params}});
          } else {
            this.setState({
              loading: false,
            });
            Message.error(result.message, 10);
          }
        }
      });
    });

  },

  setFieldArr(obj) {
    const { form } = this.props;
    let keys = form.getFieldValue('keys');
    let newArr = [];
    keys.map((k) => {
      let newObj = {};
      for (let o in obj) {
        let arr = o.split('-');
        let key = arr[0];
        if (arr[1] == k && arr[1] !== '') {
          newObj[key] = obj[o];
        }
      }
      newArr.push(newObj)
    })
    return newArr;
  },


  fetchInfo(k, value) {
    let id = this.props.location.state;
    let params = Object.assign({}, id, {costNid: value});
    let _me = this;
    Utils.sendAjax({
      url: '/tenement/cost/nextRent',
      data: JSON.stringify(params),
      callback: (result) => {
        if (result.code === '200') {
          let data = result.data;
          let newState = _me.state.dataList;
          for (let o in data) {
            let key = o +'-'+ k;
            newState[key] = data[o];
          }
          _me.setState({
            dataList: newState
          })
        } else {
          Message.error(result.message, 10);
        }
      }
    });
  },

  render () {
    const { getFieldProps, getFieldValue } = this.props.form;
    getFieldProps('keys', {
      initialValue: [0],
    });
    let _me = this;
    const formItems = getFieldValue('keys').map((k) => {
      let costNid = `costNid-${k}`
      let amount = `amount-${k}`
      let paymentStartTime = `paymentStartTime-${k}`
      let paymentEndTime = `paymentEndTime-${k}`
      let expenseTime = `expenseTime-${k}`
      let remark = `remark-${k}`
      return (
        <Row gutter={16} key={`row-${k}`}>
          <Col className="gutter-row" span={3} offset={1}>
            <div className="gutter-box">
              <Select id={costNid}  onChange={this.handleChange.bind(this, costNid)} >
                {this.state.data}
              </Select>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="text" {...getFieldProps(amount, {rules: [{validator: Utils.floatNum}]})} value={this.state.dataList[amount]} onChange={this.handleChange} disabled={ (this.state.dataList[costNid] == 'tRent' || this.state.dataList[costNid] == 'tDeposit') ? true : false}/>
            </div>
          </Col>
          <Col className="gutter-row" span={6}>
            <div className="gutter-box">
              <DatePicker id={paymentStartTime} value={this.state.dataList[paymentStartTime]}
                          onChange={this.handleChange.bind(this, paymentStartTime)}
                          style={{width: 110}}
                          disabled={(this.state.dataList[costNid] == 'tRent' || this.state.dataList[costNid] == 'tDeposit') ? true : false}/>&nbsp;至&nbsp;
              <DatePicker id={paymentEndTime} value= {this.state.dataList[paymentEndTime]}
                          onChange={this.handleChange.bind(this, paymentEndTime)}
                          style={{width: 110}} disabled={(this.state.dataList[costNid] == 'tRent' || this.state.dataList[costNid] == 'tDeposit') ? true : false}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <DatePicker id={expenseTime} value={this.state.dataList[expenseTime]}
                          onChange={this.handleChange.bind(this, expenseTime)} disabled={this.state.isFixed ? true : false}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="textarea" id={remark} value={this.state.dataList[remark]} onChange={this.handleChange} style={{height:30}} />
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Button  onClick={this.remove.bind(this, k)} disabled={ k==0 ? true : false}><Icon type="delete"/>删除</Button>
            </div>
          </Col>
        </Row>
      );
    });

    return (
      <div>
        <div className="form-group">
          <h3><span>费用缴纳</span><Button className="plus-btn" type="ghost" onClick={this.add}><Icon type="plus"/>添加费用</Button>
          </h3>
          <div>
            <div className="row-table">
              <Row className="table-title" gutter={16}>
                <Col className="gutter-row" span={3} offset={1}>
                  <div className="gutter-box">费用类别</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">缴纳金额</div>
                </Col>
                <Col className="gutter-row" span={6}>
                  <div className="gutter-box">费用日期</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">消费日期</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">备注</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box"></div>
                </Col>
              </Row>
              <Form form={this.props.form}>
                {formItems}
                <Row gutter={16}>
                  <Col className="gutter-row">
                    <FormItem wrapperCol={{ span: 5, offset: 2 }}>
                      <Button type="primary" loading={this.state.loading} onClick={this.handleSubmit}>交费</Button>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
          </div>
        </div>
      </div>
    );
  }
});

PayFree = Form.create()(PayFree);
export default PayFree;
